package com.example.sangong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sangong.dao.SgUserDao;
import com.example.sangong.entity.SgUser;
import com.example.sangong.myenum.DeleteFlagEnum;
import com.example.sangong.req.user.UserLoginReq;
import com.example.sangong.resp.UserLoginResp;
import com.example.sangong.service.SgUserService;
import com.example.sangong.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class SgUserServiceImpl extends ServiceImpl<SgUserDao, SgUser> implements SgUserService {
    @Resource
    private SgUserDao sgUserDao;

    @Override
    public UserLoginResp login(UserLoginReq req) {
        LambdaQueryWrapper<SgUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SgUser::getAccountNo, req.getAccountNo());
        queryWrapper.eq(SgUser::getDeleteFlag, DeleteFlagEnum.EFFECTIVE.getCode());
        SgUser sgUser = sgUserDao.selectOne(queryWrapper);
        if (sgUser == null) {
            throw new RuntimeException("登录失败，该用户不存在！");
        }
        if (!sgUser.getPassword().equals(req.getPassword())) {
            throw new RuntimeException("登录失败，密码不正确！");
        }
        UserLoginResp userLoginResp = new UserLoginResp();
        String token = TokenUtil.sign(sgUser.getName(), sgUser.getId()+"");
        userLoginResp.setToken(token);
        userLoginResp.setUserId(sgUser.getId());
        userLoginResp.setUserName(sgUser.getName());
        return userLoginResp;
    }
}
